package com.xiaozhichao.databafflesys.route.controller;

import cn.hutool.core.io.IoUtil;
import com.alibaba.fastjson.JSONObject;
import com.xiaozhichao.databafflesys.common.domain.CommonConstant;
import com.xiaozhichao.databafflesys.common.domain.ExceptionEnums;
import com.xiaozhichao.databafflesys.common.domain.ResultVo;
import com.xiaozhichao.databafflesys.common.utils.ReqOrder;
import com.xiaozhichao.databafflesys.route.service.RouteService;
import org.apache.commons.collections4.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author:xiaozhichao
 * @date:2021/3/22
 */
@RestController
public class RouteController {

    public Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    RouteService routeService;

    @RequestMapping("/route/{app}/{env}/{datasource}/**")
    public String route(@PathVariable String app,
                        @PathVariable String env,
                        @PathVariable String datasource,
                        HttpServletRequest request){
        final String path = request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE).toString();
        final String uri = path.substring(6);
        final String method = request.getMethod();
        logger.info("报文路由接收请求uri : {}; 请求方法 : {}; ",uri,method);
        try {
            String req = null;
            if("post".equalsIgnoreCase(method)){
                Map<String, String[]> parameterMap = request.getParameterMap();
                if(MapUtils.isEmpty(parameterMap)){
                    req = IoUtil.read(request.getInputStream(), CommonConstant.utf_8);
                }else{
                    req = ReqOrder.formData(parameterMap);
                }
            }else if("get".equalsIgnoreCase(method)){
                req = ReqOrder.queryString(request.getQueryString());
            }else{
                return JSONObject.toJSONString(ResultVo.getResult(ExceptionEnums.METHOD_NO_SUPPORT));
            }
            return routeService.route(uri,req);
        } catch (Exception e) {
            logger.error("报文路由接收请求报错",e);
        }
        return JSONObject.toJSONString(ResultVo.getResult(ExceptionEnums.DO_FAIL));
    }

    @RequestMapping("/routeFile/{app}/{env}/{datasource}/**")
    public void routeFile(@PathVariable String app,
                            @PathVariable String env,
                            @PathVariable String datasource,
                            HttpServletRequest request, HttpServletResponse response){
        final String path = request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE).toString();
        final String uri = path.substring(10);
        final String method = request.getMethod();
        logger.info("文件报文路由接收请求uri : {}; 请求方法 : {}; ",uri,method);
        try {
            String req = null;
            if("post".equalsIgnoreCase(method)){
                Map<String, String[]> parameterMap = request.getParameterMap();
                if(MapUtils.isEmpty(parameterMap)){
                    req = IoUtil.read(request.getInputStream(), CommonConstant.utf_8);
                }else{
                    req = ReqOrder.formData(parameterMap);
                }
            }else if("get".equalsIgnoreCase(method)){
                req = ReqOrder.queryString(request.getQueryString());
            }
            routeService.routeFile(uri,req,response);
        } catch (Exception e) {
            logger.error("文件报文路由接收请求报错",e);
        }
    }

}
